package handlers

import (
	"golang-master/photo-gallery/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type CategoryTagHandler struct {
	DB *gorm.DB
}

func NewCategoryTagHandler(db *gorm.DB) *CategoryTagHandler {
	return &CategoryTagHandler{DB: db}
}

// 分类相关操作
func (h *CategoryTagHandler) CreateCategory(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)

	var input struct {
		Name string `json:"name" binding:"required"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	category := models.Category{
		Name:   input.Name,
		UserID: userID,
	}

	if err := h.DB.Create(&category).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create category"})
		return
	}

	c.JSON(http.StatusOK, category)
}

func (h *CategoryTagHandler) GetCategories(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)

	var categories []models.Category
	h.DB.Where("user_id = ?", userID).Find(&categories)

	c.JSON(http.StatusOK, categories)
}

func (h *CategoryTagHandler) DeleteCategory(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)
	categoryID := c.Param("id")

	var category models.Category
	if err := h.DB.Where("id = ? AND user_id = ?", categoryID, userID).First(&category).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Category not found"})
		return
	}

	if err := h.DB.Delete(&category).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete category"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Category deleted successfully"})
}

// 标签相关操作
func (h *CategoryTagHandler) CreateTag(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)

	var input struct {
		Name string `json:"name" binding:"required"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	tag := models.Tag{
		Name:   input.Name,
		UserID: userID,
	}

	if err := h.DB.Create(&tag).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create tag"})
		return
	}

	c.JSON(http.StatusOK, tag)
}

func (h *CategoryTagHandler) GetTags(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)

	var tags []models.Tag
	h.DB.Where("user_id = ?", userID).Find(&tags)

	c.JSON(http.StatusOK, tags)
}

func (h *CategoryTagHandler) DeleteTag(c *gin.Context) {
	userID := c.MustGet("user_id").(uint)
	tagID := c.Param("id")

	var tag models.Tag
	if err := h.DB.Where("id = ? AND user_id = ?", tagID, userID).First(&tag).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Tag not found"})
		return
	}

	if err := h.DB.Delete(&tag).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete tag"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Tag deleted successfully"})
}
